﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using ExpertMIS.Entities;
using ExpertMIS.Brokers;

using System.Data;
using System.Text;

namespace ExpertMIS.Service
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class OnlineIndexService : IHttpHandler
    {
        private OnlineIndexBroker _indexBroker = new OnlineIndexBroker();
        public void ProcessRequest(HttpContext context)
        {
            if ("poll".Equals(context.Request["action"]))
            {
                context.Response.ContentType = "text/json";

                OnlineIndexEntity index = _indexBroker.NewEntity() as OnlineIndexEntity;

                index.IP = context.Request.UserHostAddress;
                index.Option = context.Request["option"];

                if (_indexBroker.SaveEntity(index, null).Code == 0)
                {
                    context.Response.Write("{success:true,text:'感谢您的投票!'}");
                }
                else
                {
                    context.Response.Write("{success:false,text:'投票失败，请重试!'}");
                }
            }
            else if ("view".Equals(context.Request["action"]))
            {
                context.Response.ContentType = "text/html";

                DataTable dt = _indexBroker.GetOptionView();

                int totalCount = 0;
                foreach (DataRowView row in dt.DefaultView)
                {
                    totalCount += Convert.ToInt32(row["F_Count"]);
                }

                StringBuilder sb = new StringBuilder();

                sb.Append("<table>");
                foreach (DataRowView row in dt.DefaultView)
                {
                    sb.Append("<tr><td style='width:120px;height:28px;vertical-align:middle;text-align:left;'>");
                    double rate = (double)Convert.ToInt32(row["F_Count"]) / totalCount;
                    sb.Append(string.Format("<div style='width:{0}%;height:18px;background-color:#1974a9;'></div>", (rate * 100).ToString("0.##")));
                    sb.Append("</td>");
                    sb.Append("<td style='width:120px;'>");
                    sb.Append(row["F_Option"]);
                    sb.Append(string.Format(" <span>{0}%</span>",(rate * 100).ToString("0.##")));
                    sb.Append("</td></tr>");
                }
                sb.Append("</table>");

                context.Response.Write(sb.ToString());
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
